<?php

namespace App\Models\Common\Passengers;

use Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

/**
 * App\Models\Common\Passengers\CommonPassengers
 *
 * @property int         $id
 * @property string      $passenger_id  乘客id
 * @property string      $identity_code 乘客证件号
 * @property Carbon|null $created_at
 * @property Carbon|null $updated_at
 * @method static Builder|CommonPassenger newModelQuery()
 * @method static Builder|CommonPassenger newQuery()
 * @method static Builder|CommonPassenger query()
 * @method static Builder|CommonPassenger whereCreatedAt($value)
 * @method static Builder|CommonPassenger whereId($value)
 * @method static Builder|CommonPassenger whereIdentityCode($value)
 * @method static Builder|CommonPassenger wherePassengerId($value)
 * @method static Builder|CommonPassenger whereUpdatedAt($value)
 * @mixin Eloquent
 */
class CommonPassenger extends Model
{
    use HasFactory;

    protected $table = 'common_passengers';
    protected $fillable
                     = [
            'passenger_id',
            'identity_code',
        ];

    public function getPassengerId()
    {
        return $this->getAttribute('passenger_id');
    }

    public function getIdentityCode()
    {
        return $this->getAttribute('identity_code');
    }

    public function getByIdentityCode(string $identity_code): ?self
    {
        $cache_key = "common_passenger:{$identity_code}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }
        $res = $this->where('identity_code', $identity_code)->first();
        if ($res) {
            Cache::put($cache_key, $res, 10 * config("trip.ttl.day"));
        }
        return $res;
    }
}
